﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebVideo.Models;

namespace WebVideo.Controllers
{
    public class IndexController : Controller
    {
        //
        // GET: /Index/
        private const int DefaultPageSize = 5;// trang tìm kiếm video
        private const int PageSize = 21; // trang video
        public ActionResult Index()
        {
            ViewBag.MetaDescription = "Trang chủ yêu quảng cáo - adv , có nhiều video quảng cáo hấp dẫn, mới lạ có thể giúp bạn kiếm tiền online dễ dàng, nhanh chóng thông qua xem quảng cáo";
            ViewBag.MetaKeywords = "quảng cáo, video, adv, online, kiếm tiền, nhanh chóng";

        
         return View();
        }
        public string DemTinnhan()
        {
            dbVideoDataContext db = new dbVideoDataContext();
              int sll = 0;
            if (Request.Cookies["UserId"] != null)
            {
                var q = db.EntityChats
                 .Where(k => k.Friend == Request.Cookies["UserId"].Value && k.Status == 1)
                 .GroupBy(a => a.UserName)
                 .Select(g => g.First());
               // ViewBag.SoLuongTinNhan = q.ToList().Count.ToString();
                 sll = q.ToList().Count;
            }
            return sll.ToString();
        }
        #region "Tất cả video"
        public ActionResult AllVideo()
        {
            try
            {
                dbVideoDataContext db = new dbVideoDataContext();
                var query = from p in db.EntityVideos
                            orderby p.Viewed, p.Date descending
                            select p;


                if (System.Web.HttpContext.Current.Request.Cookies["userId"] != null)
                {
                    string us = Request.Cookies["UserId"].Value;
                    query = from p in db.EntityVideos
                            where !(from o in db.EntityListVideoOfUsers where o.UserName == us && o.Date == DateTime.Now.Date && o.Status == 2 select o.IdVideo).Contains(p.Id)
                            orderby p.Viewed, p.Date descending
                            select p;
                }
                int sk = query.Where(g => g.Status == 1).ToList().Count;
                ViewBag.sl = query.Where(g => g.Status == 1).ToList().Count;
                return View(query.Where(g => g.Status == 1).Skip(0).Take(PageSize).ToList());

            }
            catch
            {
                return RedirectToAction("Error", "TrangChu", new { errorMsg = "Thông tin không tồn tại" });
            }
        }
        public ActionResult _AllVideo(int? page)
        {
            try
            {
                int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
                currentPageIndex = currentPageIndex * PageSize;

                dbVideoDataContext db = new dbVideoDataContext();
                var query = from p in db.EntityVideos
                            orderby p.Viewed, p.Date descending
                            select p;


                if (System.Web.HttpContext.Current.Request.Cookies["userId"] != null)
                {
                    string us = Request.Cookies["UserId"].Value;
                    query = from p in db.EntityVideos
                            where !(from o in db.EntityListVideoOfUsers where o.UserName == us && o.Date == DateTime.Now.Date select o.IdVideo).Contains(p.Id)
                            orderby p.Viewed, p.Date descending
                            select p;
                }
                return PartialView(query.Where(g => g.Status == 1).Skip(currentPageIndex).Take(PageSize).ToList());

            }
            catch
            {
                return RedirectToAction("Error", "TrangChu", new { errorMsg = "Thông tin không tồn tại" });
            }
        }
        #endregion
        public ActionResult Video()
        {
            try
            {

                dbVideoDataContext db = new dbVideoDataContext();
                var query = from p in db.EntityVideos
                            orderby p.Viewed, p.Date descending
                            select p;
                IList<EntityVideo> ds = new List<EntityVideo>();
                if (Request.Cookies["userId"] != null && Request.Cookies["UserType"].Value == "1")
                {
                    string us = Request.Cookies["UserId"].Value;
                    query = from p in db.EntityVideos
                            where !(from o in db.EntityListVideoOfUsers where o.UserName == us && o.Date == DateTime.Now.Date && o.Status == 2 select o.IdVideo).Contains(p.Id)
                            orderby p.Viewed, p.Date descending
                            select p;
                    EntityUser user = db.EntityUsers.Where(g=>g.UserName == us).First();
                    int ii = 0;
                    foreach (var item in query.Where(g => g.Status == 1).ToList())
                    {
                       
                        if (ii > 9)
                            break;
                        string check = item.Criteria ;
                        switch (check)
                        {
                            case "All":
                                    ds.Add(item);
                                    ii++;
                                break;
                            case "Age>18":
                                if (DateTime.Now.Year - user.YearBorn >= 18)
                                {
                                    ds.Add(item);
                                    ii++;
                                }
                                break;
                            case "Age<18":
                                if (DateTime.Now.Year - user.YearBorn < 18)
                                {
                                    ds.Add(item);
                                    ii++;
                                }
                                break;
                            case "Male":
                                if (user.Sex == "Nam")
                                {
                                    ds.Add(item);
                                    ii++;
                                }
                                break;
                            case "Female":
                                if (user.Sex =="Nữ")
                                {
                                    ds.Add(item);
                                    ii++;
                                }
                                break;
                            default: // city
                               if (user.City.ToString() == item.Criteria)
                                {
                                    ds.Add(item);
                                    ii++;
                                }
                                break;
                        }
                    }
                }
                else
                {
                    if (Request.Cookies["userId"] != null && Request.Cookies["UserType"].Value == "2")
                    {
                        query = from p in db.EntityVideos
                                    where p.IdBusiness == Request.Cookies["UserId"].Value
                                    orderby p.Date descending
                                    select p;
                    }
                    foreach (var item in query.Where(g => g.Status == 1).ToList().Take(9))
                    {
                        ds.Add(item);
                    }

                }
                return PartialView(ds);
               
            }
            catch
            {
                return RedirectToAction("Error", "TrangChu", new { errorMsg = "Thông tin không tồn tại" });
            }
        }

        public ActionResult sucss()
        {
            return View();
        }
        public ActionResult test(int Id)
        {

            return RedirectToAction("sucss", "Index");
        }

        public ActionResult NView(int IdVideo)
        {

            dbVideoDataContext db = new dbVideoDataContext();
            EntityVideo vs = db.EntityVideos.Where(g=>g.Id == IdVideo ).First();
            EntityListVideoOfUser l = new EntityListVideoOfUser();
           var query = db.EntityListVideoOfUsers.Where(g => g.UserName == Request.Cookies["UserID"].Value && g.IdVideo == IdVideo);
           if (query.ToList().Count() > 0)
           {
               l = query.ToList().First();
               if (l.Date != DateTime.Now.Date)
               {
                   l.Date = DateTime.Now.Date;
                   l.Status = 1;
               }
             
           }
           else if (Request.Cookies["UserType"].Value == "1")
           {
               l.UserName = Request.Cookies["UserId"].Value;
               l.IdVideo = IdVideo;
               l.Date = DateTime.Now.Date;
               l.Status = 3;
               db.EntityListVideoOfUsers.InsertOnSubmit(l);
           }
           ViewBag.MetaDescription = vs.MetaDesciption;
           ViewBag.MetaKeywords = vs.MetaKeyWord;

            db.SubmitChanges();
            return View(vs);
        }
       
        #region "Kiem tra video nguoi dung da xem ngay hien tai trong ngay chua"
        public string KiemTraVideo(int IdVideo)
        {
            try
            {
                if (Request.Cookies["UserType"].Value == "2")
                    return "error";
                dbVideoDataContext db = new dbVideoDataContext();
                string us = Request.Cookies["UserId"].Value;
                var query = from p in db.EntityListVideoOfUsers
                            where p.UserName == us && p.Date == DateTime.Now.Date && p.IdVideo == IdVideo && (p.Status == 0 || p.Status == 2)
                            select p;
                if (query.ToList().Count > 0)
                {
                    return "error";
                }
                return "complete";
            }
            catch
            {
                return "error";
            }

        }
        #endregion
         public ActionResult Error()
        {
            return View();
        }
         #region "Search"
         public ActionResult Search(string search)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            var likestr = string.Format("%{0}%", search);

          IList<EntityVideo> video = db.EntityVideos.Where(x => SqlMethods.Like(x.Name, likestr)).ToList();
          var products = video.Skip(0).Take(DefaultPageSize).ToList();
              
            ViewBag.search = search;
            ViewBag.sl = video.Count();
          return View(products);
        }
        public ActionResult AjaxPage(int? page, string search)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            currentPageIndex= currentPageIndex*DefaultPageSize ;
            var likestr = string.Format("%{0}%", search);
            dbVideoDataContext db = new dbVideoDataContext();
            IList<EntityVideo>video = db.EntityVideos.Where(x => SqlMethods.Like(x.Name, likestr)).ToList();
            var products = video.Skip(currentPageIndex).Take(DefaultPageSize).ToList();
            return PartialView("_ListSearch", products);
        }
     #endregion

        #region "những hàm liên quan đến hiện câu hỏi"
        public ActionResult checkview(int IdV)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            EntityVideo vs = db.EntityVideos.Where(g => g.Id == IdV).First();
            if (vs.Viewed == (vs.Views - 101))
            {
                return RedirectToAction("Mailer2", "Mailer", new { IdV = vs.Id });
            }


            else if (vs.Viewed >= vs.Views)
            {
                vs.Status = 3;
                db.SubmitChanges();
                return RedirectToAction("Mailer1", "Mailer", new { IdV = vs.Id });
            }
            else
            {
                return RedirectToAction("Error", "TrangChu", new { errorMsg = "Thông tin không tồn tại" });
            }
        }
       
        
        #endregion
        #region "Hiện lên câu hỏi trắc ngiệm đi kèm với hình ảnh"
        public ActionResult _ImageVideo(int IdVideo)
        {
            dbVideoDataContext db = new dbVideoDataContext();

            var likestr = string.Format("%{0}%", IdVideo.ToString() + ",");

            var query = from p in db.EntityQuestions_MultipleChoices
                        where SqlMethods.Like(p.ListVideo, likestr)
                        select p;

           // var cp = db.EntityQuestions_MultipleChoices.Where(g => g.IdVideo == IdVideo && g.Type == 1).ToList();
           
            return PartialView(query.Where(g=>g.Type == 1).ToList());

        }
        public string Check_First_Watch_Video(int IdVideo)
        {
            dbVideoDataContext db = new dbVideoDataContext();
           // string us = Request.Cookies["UserId"].Value;
            try
            {
                EntityUser us = db.EntityUsers.Where(g => g.UserName == Request.Cookies["UserId"].Value).First();
                EntityVideo vs = db.EntityVideos.Where(g => g.Id == IdVideo).First();
                var query = from p in db.EntityListVideoOfUsers
                            where p.UserName == us.UserName && p.IdVideo == IdVideo && (p.Status == 3)
                            select p;
                if (db.EntityListVideoOfUsers.Where(g=>g.UserName == us.UserName && g.IdVideo == IdVideo && g.Status == 3).Any() == false)
                {
                    //bước 1: cộng điểm cho user

                    int Diem = int.Parse(vs.EntityTypeVideo.Point.ToString());
                  
                    us.PointVideo = us.PointVideo + Diem;
                    //bước 2: cộng điểm cho người bạn đã mời user

                    if (us.UserNameRoot != null)
                    {
                        EntityUser us1 = db.EntityUsers.Where(g => g.UserName == us.UserNameRoot).First();

                        // kiểm tra xem người dùng có xem video nào trong vòng 3 ngày

                        if (db.EntityListVideoOfUsers.Where(g => g.UserName == us1.UserName && (DateTime.Now - g.Date).TotalDays <= 3).Any() == true)
                        {
                            us1.PointFriend1 = us1.PointFriend1 + (Diem * 2) / 100;
                        }

                        if (us1.UserNameRoot != null)
                        {
                            EntityUser us2 = db.EntityUsers.Where(g => g.UserName == us1.UserNameRoot).First();
                            // kiểm tra xem người dùng có xem video nào trong vòng 3 ngày

                            if (db.EntityListVideoOfUsers.Where(g => g.UserName == us2.UserName && (DateTime.Now - g.Date).TotalDays <= 3).Any() == true)
                            {
                                us2.PointFriend2 = us2.PointFriend2 + Diem / 100;
                            }


                        }
                    }
                    db.SubmitChanges();
                    // bước 3 tăng lượt view
                    EntityListVideoOfUser l = new EntityListVideoOfUser();
                    l = db.EntityListVideoOfUsers.Where(g => g.UserName == Request.Cookies["UserID"].Value && g.IdVideo == IdVideo).First();
                    l.Status = 2;

                    vs.Viewed = vs.Viewed + 1;
                    db.SubmitChanges();

                    if (vs.Viewed == vs.Views)
                    {
                        vs.Status = 3;
                        vs.Viewed_Date = DateTime.Now;
                    }
                    db.SubmitChanges();

                    return "Complete";
                }
            }
            catch
            {
            }
            return "Error";
        }
        #endregion

        #region "Câu hỏi trắc ngiệm của video"
        public ActionResult CauHoiTracNgiem(int IdVideo, int STT, string ArrR)
        {
           
                dbVideoDataContext db = new dbVideoDataContext();
                IEnumerable<EntityQuestions_MultipleChoice> cp = db.EntityQuestions_MultipleChoices.Where(g => g.IdVideo == IdVideo && g.Type == 2).ToList();
                EntityQuestions_MultipleChoice qq = new EntityQuestions_MultipleChoice();
                EntityVideo vs = db.EntityVideos.Where(g => g.Id == IdVideo).First();
                ViewBag.STT = STT + 1;
                STT = STT + 1;
                if (STT == cp.Count() - 1)
                {
                    ViewBag.Status = "True";
                }
                if (STT == -1)
                {

                    EntityQuestions_MultipleChoice mt = qq = cp.ElementAt(cp.Count() - 1);
                    EntityListQuestionMutiOfUser q = new EntityListQuestionMutiOfUser();

                    q.UserName = Request.Cookies["UserId"].Value;
                    q.IdQuestion = mt.Id;
                    q.Result = ArrR;
                    q.Date = DateTime.Now;
                    db.EntityListQuestionMutiOfUsers.InsertOnSubmit(q);
                    db.SubmitChanges();

                    //bước 1: cộng điểm cho user

                    int Diem = int.Parse(vs.EntityTypeVideo.Point.ToString());
                    EntityUser us = db.EntityUsers.Where(g => g.UserName == Request.Cookies["UserId"].Value).First();
                    us.PointVideo = us.PointVideo + Diem;
                    //bước 2: cộng điểm cho người bạn đã mời user

                    if (us.UserNameRoot != null)
                    {
                        EntityUser us1 = db.EntityUsers.Where(g => g.UserName == us.UserNameRoot).First();

                        // kiểm tra xem người dùng có xem video nào trong vòng 3 ngày

                        if (db.EntityListVideoOfUsers.Where(g => g.UserName == us1.UserName && (DateTime.Now - g.Date).TotalDays <= 3).Any() == true)
                        {
                            us1.PointFriend1 = us1.PointFriend1 + (Diem * 2) / 100;
                        }

                        if (us1.UserNameRoot != null)
                        {
                            EntityUser us2 = db.EntityUsers.Where(g => g.UserName == us1.UserNameRoot).First();
                            // kiểm tra xem người dùng có xem video nào trong vòng 3 ngày

                            if (db.EntityListVideoOfUsers.Where(g => g.UserName == us2.UserName && (DateTime.Now - g.Date).TotalDays <= 3).Any() == true)
                            {
                                us2.PointFriend2 = us2.PointFriend2 + Diem / 100;
                            }


                        }
                    }
                    db.SubmitChanges();
                    // bước 3 tăng lượt view
                    EntityListVideoOfUser l = new EntityListVideoOfUser();
                    l = db.EntityListVideoOfUsers.Where(g => g.UserName == Request.Cookies["UserID"].Value && g.IdVideo == IdVideo).First();
                    l.Status = 2;

                    vs.Viewed = vs.Viewed + 1;
                    db.SubmitChanges();

                    if (vs.Viewed == vs.Views)
                    {
                        vs.Status = 3;
                        vs.Viewed_Date = DateTime.Now;
                    }
                    db.SubmitChanges();

                }
                else
                {
                    if (STT != 0)
                    {
                        EntityQuestions_MultipleChoice mt = qq = cp.ElementAt(STT - 1);
                        EntityListQuestionMutiOfUser q = new EntityListQuestionMutiOfUser();
                        // q.Id = GetSTTMuti();
                        q.UserName = Request.Cookies["UserId"].Value;
                        q.IdQuestion = mt.Id;
                        q.Result = ArrR;
                        q.Date = DateTime.Now;
                        db.EntityListQuestionMutiOfUsers.InsertOnSubmit(q);
                        db.SubmitChanges();
                    }
                    qq = cp.ElementAt(STT);

                }
            

            return PartialView(qq);
            
        }
     
        #endregion

        #region "câu hỏi tự luận của video"
        //EntityQuestions_Essay
        public ActionResult _CauHoiTuLuan(int IdVideo, int STT, string ArrR)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            IEnumerable<EntityQuestions_Essay> cp = db.EntityQuestions_Essays.Where(g => g.IdVideo == IdVideo).ToList();
            EntityQuestions_Essay qq = new EntityQuestions_Essay();
            EntityVideo vs = db.EntityVideos.Where(g => g.Id == IdVideo).First();
            ViewBag.STT = STT + 1;
            STT = STT + 1;
            if (STT == cp.Count() - 1)
            {
                ViewBag.Status = "True";
            }
            if (STT == -1)
            {
                EntityQuestions_Essay mt = qq = cp.ElementAt(cp.Count() - 1);
                EntityListQuestionOfUser q = new EntityListQuestionOfUser();
               // q.Id = GetSTTES();
                q.UserName = Request.Cookies["UserId"].Value;
                q.IdQuestion = mt.Id;
                q.Result = ArrR;
                q.Date = DateTime.Now;
                db.EntityListQuestionOfUsers.InsertOnSubmit(q);
                db.SubmitChanges();

                //bước 1: cộng điểm cho user

                int Diem = int.Parse(vs.EntityTypeVideo.Point.ToString());
                EntityUser us = db.EntityUsers.Where(g => g.UserName == Request.Cookies["UserId"].Value).First();
                us.PointVideo = us.PointVideo + Diem;
                //bước 2: cộng điểm cho người bạn đã mời user

                if (us.UserNameRoot != null)
                {
                    EntityUser us1 = db.EntityUsers.Where(g => g.UserName == us.UserNameRoot).First();

                    // kiểm tra xem người dùng có xem video nào trong vòng 3 ngày

                    if (db.EntityListVideoOfUsers.Where(g => g.UserName == us1.UserName && (DateTime.Now - g.Date).TotalDays <= 3).Any() == true)
                    {
                        us1.PointFriend1 = us1.PointFriend1 + (Diem * 2) / 100;
                    }

                    if (us1.UserNameRoot != null)
                    {
                        EntityUser us2 = db.EntityUsers.Where(g => g.UserName == us1.UserNameRoot).First();
                        // kiểm tra xem người dùng có xem video nào trong vòng 3 ngày

                        if (db.EntityListVideoOfUsers.Where(g => g.UserName == us2.UserName && (DateTime.Now - g.Date).TotalDays <= 3).Any() == true)
                        {
                            us2.PointFriend2 = us2.PointFriend2 + Diem / 100;
                        }


                    }
                }
                db.SubmitChanges();
                // bước 3 tăng lượt view
                EntityListVideoOfUser l = new EntityListVideoOfUser();
                l = db.EntityListVideoOfUsers.Where(g => g.UserName == Request.Cookies["UserID"].Value && g.IdVideo == IdVideo).First();
                l.Status = 2;

                vs.Viewed = vs.Viewed + 1;
                db.SubmitChanges();

                if (vs.Viewed == vs.Views)
                {
                    vs.Status = 3;
                    vs.Viewed_Date = DateTime.Now;
                }
                db.SubmitChanges();

            }
            else
            {
                if (STT != 0)
                {

                    EntityQuestions_Essay mt = qq = cp.ElementAt(STT - 1);
                    EntityListQuestionOfUser q = new EntityListQuestionOfUser();
                   // q.Id = GetSTTES();
                    q.UserName = Request.Cookies["UserId"].Value;
                    q.IdQuestion = mt.Id;
                    q.Result = ArrR;
                    q.Date = DateTime.Now;
                    db.EntityListQuestionOfUsers.InsertOnSubmit(q);
                    db.SubmitChanges();
                }
                qq = cp.ElementAt(STT);

            }
            return PartialView(qq);
        }
       
        // tự luận + trắc ngiệm
        #endregion

        

        #region "Comment video"
        public ActionResult _CommentVideo(int IdVideo, string Comment, Int64 IdComment, Int64 IdEdit, Int64 IdDelete)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            if (Comment != "")
            {
                EntityCommentVideo cm = new EntityCommentVideo();
                cm.Des = Comment;
                cm.UserName = Request.Cookies["UserId"].Value;
                cm.Date = DateTime.Now;
                cm.IdVideo = IdVideo;
                cm.Likes = 0;
                db.EntityCommentVideos.InsertOnSubmit(cm);
                db.SubmitChanges();
            }
            if (IdComment > 0)
            {
                var query1   = db.EntityDetailCommentVideos.Where(g => g.IdComment == IdComment && g.UserName == Request.Cookies["UserId"].Value);
                if (query1.ToList().Count <= 0)
                {
                    EntityCommentVideo cm = db.EntityCommentVideos.Where(g => g.Id == IdComment).First();
                    cm.Likes = cm.Likes + 1;
                    EntityDetailCommentVideo d = new EntityDetailCommentVideo();
                    d.UserName = Request.Cookies["UserId"].Value;
                    d.IdComment = IdComment;
                    db.EntityDetailCommentVideos.InsertOnSubmit(d);
                }
                   
                db.SubmitChanges();
            }
            //if (IdEdit > 0)
            //{
            //    EntityCommentVideo cm = db.EntityCommentVideos.Where(g => g.Id == IdEdit).First();
            //    cm.Des = Comment;
            //    db.SubmitChanges();
            //}
            if (IdDelete > 0)
            {
                EntityCommentVideo cm = db.EntityCommentVideos.Where(g => g.Id == IdDelete).First();
                db.EntityCommentVideos.DeleteOnSubmit(cm);
                db.SubmitChanges();
            }
            var query = db.EntityCommentVideos.Where(g => g.IdVideo == IdVideo);
            ViewBag.IdVideos = IdVideo;
            return PartialView(query.ToList());
        }

        #endregion
        public ActionResult ThanhVienCaoDiem()
        {
            try
            {
                dbVideoDataContext db = new dbVideoDataContext();
                var query = from p in db.EntityUsers
                            orderby (p.PointVideo + p.PointFriend1+p.PointFriend2) descending 
                            select p;
                return PartialView(query.ToList().Take(10));
            }
            catch
            {
                return RedirectToAction("Error", "TrangChu", new { errorMsg = "Thông tin không tồn tại" });
            }
        }
        public ActionResult HoTro()
        {
                dbVideoDataContext db = new dbVideoDataContext();
                var query = from p in db.EntitySupportStaffs
                            select p;
                return PartialView(query.ToList().Take(5));    
        }
        public ActionResult QuangCao()
        {
            dbVideoDataContext db = new dbVideoDataContext();
            EntityThongBao qc = db.EntityThongBaos.Where(g=>g.Id == 1).First();
            ViewBag.quangcao = qc.Status;
            return PartialView(qc);
        }
    }
}
